<template>
	<view class="normal-login-container">
		<!-- 搜索 -->
		<view class="search-area" style="margin-top: 10px;">
			<view class="search-box">
				<img style="width: 23px;height: 23px;" src="https://shalong.taiyanyue.top/images/md-search1.png" alt="" />
				<input class="search-input" placeholder="搜索活动" v-model="searchValue" @confirm="handleSearch" />
			</view>
			<view class="location-box" @click="showLocationPopup">
				<img style="width: 23px;height: 23px;" src="https://shalong.taiyanyue.top/images/riLine-map-pin-line1.png" alt="" />
				<text>{{ currentLocation || '全国' }}</text>
			</view>
		</view>

		<!-- 横向滑动切换 -->
		<scroll-view class="switch-scroll" scroll-x="true" scroll-with-animation scroll-left="0">
			<view class="switch">
				<view v-for="(tab, index) in tabs" :key="index" :class="{ 'active': currentTab === index }"
					@click="switchTab(index, tab.activity_category_id)">
					{{ tab.activity_category_name }}
				</view>
			</view>
		</scroll-view>

		<!-- 列表区域 -->
		<view class="list-container">
			<view class="mox">
				<view class="tom" v-for="(item, index) in list" :key="index" @click="goToDetail(item)">
					<view class="tom-img">
						<img style="width: 100%;object-fit: contain;" :src="item.activity_cover_path" alt="" />
					</view>
					<view class="tom-som">
						<view>
							<view class="tom-som-h" style="display: flex;justify-content: space-between;">
								<div>{{ item.activity_title }}</div>
								<view style="position: absolute;right: 12px;">
									<text class="tom-som-span">{{ item.activity_price }}元</text>/位
								</view>
							</view>
							<view>{{ item.activity_describe }}</view>
						</view>

					</view>
					<view class="tom-fixed">
						<view style="font-weight: 600;">{{ item.year }}</view>
						<view style="font-size: 10px;margin-top: -4px;">——</view>
						<view style="font-weight: 600;font-size: 10px;margin-top: -4px;">{{ item.month }}月</view>
					</view>
				</view>
			</view>

			<!-- 加载提示 -->
			<view class="loading-more" v-if="loading">加载中...</view>
			<view class="no-more" v-if="noMore && list.length >= 0">没有更多数据了</view>
		</view>

		<view style="width: 100%;height: 80px;"></view>
		<!-- tabbar -->
		<custom-tabbar :current="currentTabIndex" />
		<!-- 定位弹窗 -->
		<uni-popup ref="locationPopup" type="bottom">
		  <view class="location-popup">
		    <!-- 弹窗头部 -->
		    <view class="popup-header">
		      <view class="title">选择城市</view>
		      <view class="close" @click="hideLocationPopup">×</view>
		    </view>
		
		    <!-- 搜索框 -->
		    <view class="city-search">
		      <img src="https://shalong.taiyanyue.top/images/md-search1.png" alt="" />
		      <input v-model="searchCityName" placeholder="搜索城市" @input="filterCities" />
		    </view>
		
		    <scroll-view scroll-y="true" class="city-list">
		      <!-- 默认全国选项 -->
		      <view class="city-item" :class="{ active: currentLocation === '全国' }" @click="selectCity({ district_id: 0, district_name: '全国' })">
		        <view class="city-name">全国</view>
		        <view class="location-icon" v-if="currentLocation === '全国'">✓</view>
		      </view>
		
		      <!-- 当前定位结果（仅显示，不自动选中） -->
		      <view class="current-location-section" v-if="currentCity.district_name && currentCity.district_name !== '全国'">
		        <view class="section-title">当前定位</view>
		        <view class="city-item" @click="selectCity({ district_id: currentCity.district_id, district_name: currentCity.district_name })">
		          <view class="city-name">{{ currentCity.district_name }}</view>
		          <view class="location-icon" v-if="currentLocation === currentCity.district_name">✓</view>
		        </view>
		      </view>
		
		      <!-- 城市列表 -->
		      <div v-for="(group, letter) in filteredCityGroups" :key="letter">
		        <view class="city-group-title">{{ letter }}</view>
		        <view 
		          v-for="city in group" 
		          :key="city.district_id" 
		          class="city-item" 
		          :class="{ active: currentLocation === city.district_name }"
		          @click="selectCity(city)"
		        >
		          <view class="city-name">{{ city.district_name }}</view>
		          <view class="location-icon" v-if="currentLocation === city.district_name">✓</view>
		        </view>
		      </div>
		
		      <view v-if="Object.keys(filteredCityGroups).length === 0" class="no-results">
		        未找到相关城市
		      </view>
		    </scroll-view>
		  </view>
		</uni-popup>
	</view>
</template>

<script>
	import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';
	import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue';
	import {
		activity_getHomeActivityList,
		activity_getHomeActivityCateList,
		common_getCityList
	} from '@/api/system/user.js';

	export default {
		components: {
			CustomTabbar,
			uniPopup
		},
		data() {
			return {
				currentTabIndex: 1,
				currentTab: 0,
				tabs: [],
				list: [],
				searchValue: "",
				currentLocation: "全国",
				page: 1,
				size: 5,
				loading: false,
				noMore: false,
				count: 0,
				activity_category_id: 0,
				city_id: 0,
				dizhi: [],
				searchCityName: "",
				cityGroups: {},
				currentCity: {}, // 当前定位城市
				isLocating: false // 是否正在定位中
			}
		},
		computed: {
			filteredCityGroups() {
				if (!this.searchCityName) {
					// 过滤掉当前定位城市
					const filteredGroups = {};
					for (const letter in this.cityGroups) {
						const filteredCities = this.cityGroups[letter].filter(city =>
							!this.currentCity.district_id ||
							city.district_id !== this.currentCity.district_id
						);
						if (filteredCities.length > 0) {
							filteredGroups[letter] = filteredCities;
						}
					}
					return filteredGroups;
				}

				const result = {};
				for (const letter in this.cityGroups) {
					const cities = this.cityGroups[letter].filter(city =>
						(!this.currentCity.district_id || city.district_id !== this.currentCity.district_id) &&
						(city.district_name.includes(this.searchCityName) ||
							(city.district_spell && city.district_spell.includes(this.searchCityName)))
					);

					if (cities.length > 0) {
						result[letter] = cities;
					}
				}
				return result;
			}
		},
		created() {
			this.initData();
		},
		methods: {
			async initData() {
				await this.common_getCityList();
				await this.activity_getHomeActivityCateList();

				this.activity_getHomeActivityList();
			},

			// 获取当前定位
			async getCurrentLocation() {
				this.isLocating = true;
				try {
                   let thsi=this;
					wx.getLocation({
						type: 'wgs84', // 返回可以用于wx.openLocation的经纬度
						success: function(res) {
							console.log(res)
							const latitude = res.latitude; // 纬度
							const longitude = res.longitude; // 经度
							const key = 'AUXBZ-JL5CT-SHIXN-L76NN-VP7F3-MLFB7'; // 替换为实际Key
							const url =
								`https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}&get_poi=0`;

							uni.request({
								url,
								success: (res) => {
									if (res.data.status === 0) {
										const address = res.data.result.address_component;
										const province = address.province;
										const citys = address.city;
										const district = address.district;
										console.log('省市区:', province, citys, district);
										console.log(thsi.dizhi,'222')
										const shenyang = thsi.dizhi.find(city => city
											.district_name == citys);
                                        console.log(shenyang,'11111')
										if (shenyang) {
											thsi.currentCity = {
												...shenyang
											};
											// thsi.currentLocation = citys;
											thsi.city_id = shenyang.district_id;
											 console.log(thsi.currentCity,'11111')
										}
									}
								},
								fail: (err) => {
									console.error('逆地理编码失败:', err);
								}
							});
						},
						fail: function(err) {
							console.error('获取位置失败', err);
						}
					});
				} catch (error) {
					console.error('定位失败:', error);
					// 定位失败使用默认值
					this.currentCity = {
						district_id: 210100,
						district_name: "沈阳市",
						district_initial: "S"
					};
					this.currentLocation = "沈阳市";
					this.city_id = 210100;
				} finally {
					this.isLocating = false;
				}
			},
			// 显示定位弹窗
			showLocationPopup() {
				this.$refs.locationPopup.open();
				this.getCurrentLocation();
				this.searchCityName = "";
			},

			// 隐藏定位弹窗
			hideLocationPopup() {
				this.$refs.locationPopup.close();
				this.searchCityName = "";
			},

			// 获取城市列表
			async common_getCityList() {
				try {
					const data = await common_getCityList();
					this.dizhi = data.content.data || [];
					this.groupCities();
				} catch (error) {
					console.error('获取城市列表失败:', error);
				}
			},

			// 城市分组
			groupCities() {
				const groups = {};
				this.dizhi.forEach(city => {
					const initial = city.district_initial || '#';
					if (!groups[initial]) {
						groups[initial] = [];
					}
					groups[initial].push(city);
				});

				// 按字母排序
				const sortedKeys = Object.keys(groups).sort();
				this.cityGroups = {};
				sortedKeys.forEach(key => {
					this.cityGroups[key] = groups[key];
				});
			},

			// 搜索城市
			filterCities() {
				// 搜索逻辑由计算属性处理
			},

			// 获取活动分类
			async activity_getHomeActivityCateList() {
				try {
					const data = await activity_getHomeActivityCateList({
						page: 1,
						size: 999
					});
					this.tabs = data.content.data || [];
					this.tabs.unshift({
						activity_category_id: 0,
						activity_category_name: '全部'
					});
				} catch (error) {
					console.error('获取活动分类失败:', error);
				}
			},

			// 获取活动列表
			async activity_getHomeActivityList() {
				if (this.loading) return;
				this.loading = true;

				try {
					const params = {
						page: this.page,
						size: this.size,
						search: this.searchValue,
						activity_category_id: this.activity_category_id,
						city_id: this.city_id
					};

					const data = await activity_getHomeActivityList(params);
					const newItems = (data.content.data || []).map(item => ({
						...item,
						year: '',
						month: ''
					}));

					// 处理日期
					newItems.forEach(item => {
						if (item.created_at) {
							const dateStr = item.created_at;
							const datePart = dateStr.split(" ")[0];
							const [year, month] = datePart.split("-");
							item.year = year;
							item.month = month;
						}
					});

					// 分页处理
					if (this.page === 1) {
						this.list = newItems;
					} else {
						this.list = [...this.list, ...newItems];
					}

					// 判断是否还有更多数据
					this.count = data.content.count || 0;
					this.noMore = this.list.length >= this.count || newItems.length < this.size;

				} catch (error) {
					console.error('加载活动列表失败:', error);
					if (this.page > 1) {
						this.page--;
					}
				} finally {
					this.loading = false;
				}
			},

			// 切换分类
			switchTab(index, id) {
				this.currentTab = index;
				this.activity_category_id = id;
				this.page = 1;
				this.noMore = false;
				this.activity_getHomeActivityList();
			},

			// 跳转详情页
			goToDetail(item) {
				const params = encodeURIComponent(JSON.stringify(item));
				uni.navigateTo({
					url: `/pages/activityDeatails?data=${params}`
				});
			},

			// 处理搜索
			handleSearch() {
				this.page = 1;
				this.noMore = false;
				this.activity_getHomeActivityList();
			},

			// 下拉刷新
			async onPullDownRefresh() {
				this.page = 1;
				this.noMore = false;
				await this.activity_getHomeActivityList();
				uni.stopPullDownRefresh();
			},

			// 上拉加载更多
			onReachBottom() {
				if (!this.noMore && !this.loading) {
					this.page++;
					this.activity_getHomeActivityList();
				}
			},

			// 选择城市
			selectCity(city) {
			  this.city_id = city.district_id;
			  this.currentLocation = city.district_name;
			  this.hideLocationPopup();
			  this.page = 1;
			  this.noMore = false;
			  this.activity_getHomeActivityList();
			}
		}
	}
</script>

<style lang="less" scoped>
	/* 基础样式 */
	.normal-login-container {
		background-color: #f8f8f8;
		min-height: 100vh;
	}

	/* 搜索区域样式 */
	.search-area {
		display: flex;
		align-items: center;
		padding: 10px 12px;
		background-color: #fff;

		.search-box {
			flex: 1;
			display: flex;
			align-items: center;
			background-color: #f5f5f5;
			border-radius: 20px;
			padding: 6px 12px;
			margin-right: 10px;

			.search-input {
				flex: 1;
				margin-left: 8px;
				font-size: 14px;
				color: #333;
			}
		}

		.location-box {
			display: flex;
			align-items: center;
			padding: 6px 10px;
			background-color: rgba(51, 153, 102, 0.1);
			border-radius: 20px;
			color: #339966;
			font-size: 14px;

			text {
				margin-left: 4px;
				white-space: nowrap;
			}
		}
	}

	/* 分类切换样式 */
	.switch-scroll {
		width: 100%;
		white-space: nowrap;
		background: #ffffff;
		padding-bottom: 15px;
           
		.switch {
			display: inline-block;
			width: auto;
			padding: 0 12px;

			view {
				display: inline-block;
				padding: 6px 16px;
				margin-right: 10px;
				font-size: 14px;
				color: #888888;
				border-radius: 20px;
				background: #f5f5f5;

				&.active {
					color: #51a77c;
					background: rgba(81, 167, 124, 0.1);
					font-weight: 500;
				}
			}
		}
	}

	/* 列表容器样式 */
	.list-container {
		background-color: #f4f4f4;
		padding: 10px 0;
		min-height: calc(100vh - 200px);

		.mox {
			width: 93%;
			margin-left: 12px;
		}

		.tom {
			width: 100%;
			border-radius: 12px;
			background: #ffffff;
			overflow: hidden;
			box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
			margin-bottom: 20px;
			position: relative;

			.tom-fixed {
				position: absolute;
				top: 0;
				right: 30px;
				background: #339966;
				width: 60px;
				text-align: center;
				color: #ffffff;
				padding-top: 3px;
				padding-bottom: 3px;
				border-radius: 0% 0% 35% 35%;
			}

			.tom-img {
				width: 100%;
				height: 180px;
				background-color: #f5f5f5;

				img {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}
			}

			.tom-som {
				padding: 20px 12px 20px 25px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				color: #339966;
				font-weight: 500;
				font-size: 13px;

				.tom-som-h {
					font-weight: 600;
					font-size: 16px;
					margin-bottom: 10px;
					color: #333;
				}

				.tom-som-span {
					font-weight: 600;
					font-size: 18px;
					color: #ff5a5f;
				}
			}
		}
	}

	/* 加载提示样式 */
	.loading-more,
	.no-more {
		text-align: center;
		padding: 20rpx;
		color: #999;
		font-size: 14px;
	}

	.no-more {
		color: #ccc;
	}

	/* 定位弹窗样式 */
	.location-popup {
		background-color: #fff;
		border-radius: 16px 16px 0 0;
		padding: 20px;
		max-height: 70vh;
		display: flex;
		flex-direction: column;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-bottom: 20px;
			border-bottom: 1px solid #eee;

			.title {
				font-size: 18px;
				font-weight: 600;
				color: #333;
			}

			.close {
				font-size: 24px;
				color: #999;
				padding: 0 10px;
			}
		}

		.city-search {
			display: flex;
			align-items: center;
			padding: 12px 0;
			border-bottom: 1px solid #eee;

			img {
				width: 18px;
				height: 18px;
				margin-right: 8px;
			}

			input {
				flex: 1;
				font-size: 14px;
				color: #333;
			}
		}

		.city-list {
			flex: 1;
			overflow-y: auto;
			padding: 15px 0;

			.current-location-section {
				padding: 10px 0;
				border-bottom: 1px solid #f5f5f5;

				.section-title {
					font-size: 12px;
					color: #999;
					margin-bottom: 8px;
					padding: 0 15px;
				}
			}

			.city-group-title {
				padding: 15px 15px 8px;
				font-size: 14px;
				font-weight: 600;
				color: #333;
				background-color: #fff;
			}

			.city-item {
				padding: 12px 15px;
				font-size: 15px;
				color: #333;
				border-bottom: 1px solid #f5f5f5;
				display: flex;
				justify-content: space-between;
				align-items: center;

				&.current-location {
					color: #51a77c;
					font-weight: 500;
				}

				.location-icon {
					color: #51a77c;
					font-size: 16px;
				}
			}
		}

		.no-results {
			text-align: center;
			padding: 20px;
			color: #999;
			font-size: 14px;
		}
	}
</style>